package cn.com.tuns.assess.qsb.frame.util;

import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

public class OkHttpUtil {

    public String syncGet(String url,String[] key,String[] value) {
        String newUrl=encodeUrl(url,key,value);
        return syncGet(newUrl);
    }
    /**
     * get 同步Get同求
     *
     * @param url url
     * @return
     */
    public String syncGet(String url) {
        String result = null;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public void nonSyncGet(String url,String[] key,String[] value, Callback responseCallback) {
        String newUrl=encodeUrl(url,key,value);
        nonSyncGet(newUrl,responseCallback);
    }

    /**
     * get 异步Get同求
     *
     * @param url url
     * @return
     */
    public void nonSyncGet(String url, Callback responseCallback) {
        String result = null;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(responseCallback);
    }

    public String syncPost(String url,String[] key,String[] value,String json) {
        String newUrl=encodeUrl(url,key,value);
        return syncPost(newUrl,json);
    }

    /**
     * get 同步Post同求
     *
     * @param url url
     * @return
     */
    public String syncPost(String url,String json) {
        String result = null;
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                result = response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public void nonSyncPost(String url,String[] key,String[] value,String json, Callback responseCallback) {
        String newUrl=encodeUrl(url,key,value);
        nonSyncPost(newUrl,json,responseCallback);
    }

    /**
     * get 异步Post同求
     *
     * @param url url
     * @return
     */
    public void nonSyncPost(String url,String json, Callback responseCallback) {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            client.newCall(request).enqueue(responseCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String upload(String url, File file)  {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();
        Request request = new Request.Builder()
                .header("Authorization", "ClientID" + UUID.randomUUID())
                .url(url)                .post(requestBody)
                .build();
        Response response =null;
        String result = null;
        try {
            response=client.newCall(request).execute();
            if (response.isSuccessful()) {
                result = response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

    public String encodeUrl(String url,String[] key,String[] value){
        int len=Math.max(key.length,value.length);
        StringBuilder sb=new StringBuilder();
        if(url.indexOf("?")>=0)
        {
            sb.append("&");
        }
        else {
            sb.append("?");
        }
        try {

            for(int i=0;i<len;i++)
            {
                if(sb.length()>0)
                {
                    sb.append("&");
                }
                sb.append(key[i]);
                sb.append("=");

                sb.append(URLEncoder.encode(StrUtil.nullToStr(value[i]) , "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return url;
        }


        return url+sb.toString();
    }
}
